//
//  GameRootController.m
//  ELife
//
//  Created by xiaozhi on 11-5-13.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "GameRootController.h"
#import "GameListController.h"
#import "GameRechargeController.h"
#import "ELifeAppDelegate.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "GameCardModel.h"
#import "GameGoodsInfo.h"
@implementation GameRootController
GameCardModel *_selectedModel;

@synthesize gameNameTextField, nextButton, qqButton, pickGameButton, inputContainer;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{

    [_gameCardModelList release];

    [gameNameTextField release];
    [nextButton release];
    [qqButton release];
    [pickGameButton release];
    [inputContainer release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:@"网游"];
   
    inputContainer.layer.cornerRadius = 8;
    inputContainer.layer.masksToBounds = YES;
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - network

- (void)requestCardList:(NSString *)action
{
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍后"];
    
    NSString *host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSString *urlStr = [host stringByAppendingString:@"ofcard.php"];
    
    static NSString *classId = @"22"; // 这个id现在是固定的
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlStr], @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
    [param setObject:action forKey:@"action"];
    [param setObject:classId forKey:@"class_id"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [[app httpRequestPoint]openUrl:dic
                         postParam:param target:self];
    
}

// open game list
-(void)openGameList
{
    GameListController  *gameListController = [[GameListController alloc] initWithNibName:@"GameListcontroller" bundle:nil];
    
    [gameListController setListener:self];
    [self.navigationController pushViewController:gameListController animated:YES];
    [gameListController release];
}


- (void)iRequestFinished:(NSData *)response
{
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    
    //某个具体节点的文本内容
    GDataXMLElement* gamesElement = [[bodyElement elementsForName:@"small_class_list"]objectAtIndex:0];
    NSLog(@"--------gamesElement:%@", gamesElement);
    
    NSArray *gameArr = [gamesElement children];
    
    _gameCardModelList =  [[NSMutableArray alloc] initWithCapacity:[gameArr count]];
    for (int i = 0; i<[gameArr count]; i++) {
        GDataXMLElement *item = [gameArr objectAtIndex:i];
        NSLog(@"--------item:%@", item);
        GameCardModel *gameCard = [[GameCardModel alloc]init];
        gameCard.cardId = [[[item elementsForName:@"cardid"]objectAtIndex:0]stringValue];
        NSLog(@"--------cardId:%@", gameCard.cardId);
        gameCard.cardName = [[[item elementsForName:@"othername"]objectAtIndex:0]stringValue];
        NSLog(@"--------cardName:%@", gameCard.cardName);
        
        NSString *goodsCountStr = [[[item elementsForName:@"goodscount"]objectAtIndex:0]stringValue];
        gameCard.goodsCount = [goodsCountStr intValue];
        NSLog(@"--------goodsCount:%d", gameCard.goodsCount);
        gameCard.goodsList = [[NSMutableArray alloc]initWithCapacity:10];
        
        [_gameCardModelList addObject:gameCard];
        [gameCard release];
    }
    
    // 隐藏进度条
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app hideProgressDialog];
    
    _isSecondList = NO;
    [self openGameList];
}

-(BOOL)checkValidate
{
    if([gameNameTextField.text length] == 0) {
        // show dialog
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"请先输入游戏名称" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return NO;
    }
    
    return YES;
}


#pragma mark - next step
- (void) nextStep:(GameGoodsInfo *)goodsInfo
{
    //todo go next
    static NSString *nibName = @"GameRechargeController";
    GameRechargeController *controller = [[GameRechargeController alloc] initWithNibName:nibName bundle:nil state:(_state) goodsInfo:goodsInfo];
    
    [self.navigationController pushViewController:controller animated:YES];
    self.navigationController.navigationBarHidden = NO;
    [controller release];
}

- (void)requestOtherList
{
    static NSString *action = @"get_small_class_list";
    [self requestCardList:action];
}

- (void)requestQQList
{
    static NSString *action = @"get_qq_class_list";
    [self requestCardList:action];
}

-(void)action:(id)sender
{
    if(sender == qqButton) {
        _state = (_state == STATE_QQ) ? STATE_OTHER : STATE_QQ;
        switch (_state) {
            case STATE_OTHER:
                [self setTitle:TITLE_QQ];
                [qqButton setTitle:TEXT_QQ forState:UIControlStateNormal];
                break;
            case STATE_QQ:
                [self setTitle:TITLE_OTHER];
                [qqButton setTitle:TEXT_OTHER forState:UIControlStateNormal];
                break;
        }
        gameNameTextField.text = @"";
    } else if(sender == nextButton) {
        BOOL isValidate = [self checkValidate];
        if (isValidate) {
            [self nextStep:_selectedGoodsInfo];
        }
    } else if(sender == pickGameButton) {
        switch (_state) {
            case STATE_OTHER:
                [self requestOtherList];
                break;
            case STATE_QQ:
                [self requestQQList];
                break;
        }
    }
}

- (void)requestGoodsList:(GameCardModel *)selectedModel
{    
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍后"];
    
    NSString *host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSString *urlStr = [host stringByAppendingString:@"ofcard.php"];
    
    static NSString *action = @"get_goods_list";
    NSString *class_id = selectedModel.cardId;
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlStr], @"requestGoodsListFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
    [param setObject:action forKey:@"action"];
    [param setObject:class_id forKey:@"class_id"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    [[app httpRequestPoint]openUrl:dic
                         postParam:param target:self];
}


- (void)requestGoodsListFinished:(NSData *)response
{
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    NSLog(@"--------body:%@", bodyElement);
    //某个具体节点的文本内容
    GDataXMLElement* gamesElement = [[bodyElement elementsForName:@"goods_list"]objectAtIndex:0];
    NSLog(@"--------goods_list:%@", gamesElement);
    
    NSArray *gameArr = [gamesElement children];
    
    GameCardModel *gameCard = _selectedGameCardModel;
    
    for (int i = 0; i<[gameArr count]; i++) {
        GDataXMLElement *item = [gameArr objectAtIndex:i];
        GameGoodsInfo *goodsInfo = [[GameGoodsInfo alloc]init];
        NSLog(@"--------item:%@", item);
        goodsInfo.cardId = [[[item elementsForName:@"cardid"]objectAtIndex:0]stringValue];
        NSLog(@"--------gameId:%@", goodsInfo.cardId);
        goodsInfo.otherName = [[[item elementsForName:@"othername"]objectAtIndex:0]stringValue];
        NSLog(@"--------cardName:%@", goodsInfo.otherName);
        goodsInfo.pervalue = [[[item elementsForName:@"pervalue"]objectAtIndex:0]stringValue];
        NSLog(@"--------pervalue:%@", goodsInfo.pervalue);
        goodsInfo.salevalue= [[[item elementsForName:@"salevalue"]objectAtIndex:0]stringValue];
        NSLog(@"--------salevalue:%@", goodsInfo.salevalue);
        
        NSString *amountsStr = [[[item elementsForName:@"amounts"]objectAtIndex:0]stringValue];
        NSArray *amounts = [amountsStr componentsSeparatedByString:@","];
        
        goodsInfo.amounts = amounts;
        
        NSLog(@"-------amounts:%@", amounts);
        
        [gameCard.goodsList addObject:goodsInfo];
    }
    
    // 隐藏进度条
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app hideProgressDialog];
    
    // 如果需要打开2级列表
    if (_isSecondList == NO && gameCard.goodsCount > 0) {
        _isSecondList = YES;
        [self openGameList];
    } else {
        // 直接打开1级列表 
        _selectedGoodsInfo = [gameCard.goodsList objectAtIndex:0];
        gameNameTextField.text = _selectedGoodsInfo.otherName;
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma markend

- (NSString *)getCellName:(NSInteger)index
{
    if (_isSecondList) {
        GameCardModel *selectedModel = _selectedGameCardModel;
        GameGoodsInfo *goodsInfo = [selectedModel.goodsList objectAtIndex: index];
        return goodsInfo.otherName;
    }
    
    GameCardModel *gameCard = [_gameCardModelList objectAtIndex:index];
    return gameCard.cardName;

}

- (BOOL)hasNextLevel:(NSInteger)index
{
    GameCardModel *cardModel = [_gameCardModelList objectAtIndex:index];
    if (_isSecondList == NO
        && cardModel.goodsCount > 0) {
        return YES;
    }
    return NO;
}

- (void)didSelected:(NSInteger)index
{
    if (_isSecondList == YES) {
        NSMutableArray *goodsList = _selectedGameCardModel.goodsList;
        GameGoodsInfo *goodsInfo = [goodsList objectAtIndex:index];
        _selectedGoodsInfo = goodsInfo;
        gameNameTextField.text = goodsInfo.otherName;
        [self.navigationController popToViewController:self animated:YES];
    } else {
        _selectedGameCardModel = [_gameCardModelList objectAtIndex:index];
        // 请求goodslist
        [self requestGoodsList:_selectedGameCardModel];
    }
}

- (NSInteger)getCount
{
    if (_isSecondList) {
        GameCardModel *selectedModel = _selectedGameCardModel;
        return [selectedModel.goodsList count];
    }
   return [_gameCardModelList count];
}

@end
